package com.itheima.controller;

import com.itheima.resources.UploadUtils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/upload")
public class UploadController {
    @RequestMapping(value = "/pictureUpload.do",name = "图片上传")
    public String pictureUpload(@RequestParam("upload") MultipartFile file){
        //try..catch  上传异常跳转到失败页面
        try {
            System.out.println(file);
            //使用工具类获取一个UUID的文件名
            String uuidfilename = UploadUtils.generateRandonFileName(file.getOriginalFilename());

            //创建一个Client对象
            Client client=new Client();

            //传递路径参数 获取资源对象
            WebResource resource = client.resource("http://127.0.0.1:9001/uploads/" + uuidfilename);
            //上传字节文件
            resource.put(file.getBytes());

            return "redirect:/success.html";
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:/error.html";
        }
    }
}
